<?php 
/* 
 * This file is part of TCDB. 
 * 
 * Copyright (C) 2000-2009 
 * Technology Consultant Corps 
 * Grinnell College 
 * Grinnell, IA, 50112 
 * tc@grinnell.edu 
 * 
 * TCDB is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version. 
 * 
 * TCDB is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with TCDB. If not, see <http://www.gnu.org/licenses/>. 
 * 
 
 ============================================================================= 
 
 * edit_users.php -- Allows an admin to change information about a given user
 *		     Also allows an admin to reset a user's password, change
 *		     certification info, add comments, and delete a user from the DB
 *
 *		     Much of this code is taken straight from update_info.php;
 *		     here, however, we can see and edit more info... such is 
 *		     the nature of administration
 * 
 * Author: Dylan J. Sather
 * Created: 2009-07-13 
 * Last edited: 2009-07-29
 *
 * Thanks to James Michael-Hill and CM Lubinski for their work on edit_users.php
 * since October 2003
 */ 
 
$page_title = "edit_users.php"; 

require('init.php'); 
require('require_login.php'); 
require('require_admin.php'); 
require('fpdf/fpdf.php');

// If the user_id isn't set, display an error message and let the admin choose a user
if (!isset($_GET['user_id'])) {
    include('header.php'); 

    echo "  <div class='content_box'> <!-- CONTENT div -->
    <h2>Cannot display information -- no user ID specified</h2>
    <h3>Please choose a user from the list below</h3>\n";

    // Pull users from the list, sorted by last name
    $query = "SELECT first_name, last_name, id
	      FROM users
	      ORDER BY last_name";

    // If the query is successful, display the list of users
    if ($result = $mysqli->query($query, MYSQLI_STORE_RESULT)) {
	echo "<form method='get' action='edit_users.php'>
	    <div> <!-- FORM div -->
	      <select name='user_id'>\n";

	while (list($first_name, $last_name, $user_id) = $result->fetch_row()) {
	    echo "<option value='$user_id'>$first_name $last_name</option>\n";
	}

	echo "</select><br />
	      <input class='big_margins' type='submit' value='Edit Info' />
	    </div> <!-- End FORM div -->
	  </form>\n";
    }

    else {
	echo "<p>Couldn't pull user information from the DB; check the DB connection</p>\n";
    }
}

// Otherwise, we have a user ID and we can move on
else {
    
    /* There are five types of form data we can change: basic, certification, 
       other, password, and comments
       
       We can also delete a user, which requires a large block of code
       
       We have to see which data the admin is changing, since it might be stored in multiple 
       tables. This also helps logically separate our code. This is accomplished by including 
       a hidden 'action' field that determines which action we're performing */

    if (isset($_POST['action'])) {

	// Display a message about what updated or failed to update
	$message = "";

	// We need to do some magic to make sure $receive_sub_emails and $publish_schedule are properly set
	$receive_sub_emails = (isset($_POST['receive_sub_emails'])) ? $_POST['receive_sub_emails']  : FALSE;
	$publish_schedule = (isset($_POST['publish_schedule'])) ? $_POST['publish_schedule'] : FALSE;
	$currently_here = (isset($_POST['currently_here'])) ? $_POST['currently_here'] : FALSE;

	/* We have to send the value "1" for TRUE to the MySQL DB, since it doesn't 
	   read PHP's "trueness" as TRUE; send 0 for FALSE */
	if ($receive_sub_emails)
	    $receive_sub_emails = 1;
	else
	    $receive_sub_emails = 0;
	if ($publish_schedule)
	    $publish_schedule = 1;
	else
	    $publish_schedule = 0;
	if ($currently_here)
	    $currently_here = 1;
	else
	    $currently_here = 0;

	switch ($_POST['action']) {
	    case "basic":
		$query = sprintf("UPDATE users
				  SET first_name = '%s',
				      last_name = '%s',
				      email = '%s',
				      campus_phone = '%s',
				      cell_phone = '%s',
				      box_num = '%s',
				      major = '%s',
				      concentration = '%s',
				      pcard_id = '%s',
				      receive_sub_emails = '%s',
				      publish_schedule = '%s',
				      currently_here = '%s'
				  WHERE id = '%s'",
			      mysqli_real_escape_string($mysqli, $_POST['first_name']),
			      mysqli_real_escape_string($mysqli, $_POST['last_name']),
			      mysqli_real_escape_string($mysqli, $_POST['email']),
			      mysqli_real_escape_string($mysqli, $_POST['campus_phone']),
			      mysqli_real_escape_string($mysqli, $_POST['cell_phone']),
			      mysqli_real_escape_string($mysqli, $_POST['box_num']),
			      mysqli_real_escape_string($mysqli, $_POST['major']),
			      mysqli_real_escape_string($mysqli, $_POST['concentration']),
			      mysqli_real_escape_string($mysqli, $_POST['pcard_id']),
			      mysqli_real_escape_string($mysqli, $receive_sub_emails),
			      mysqli_real_escape_string($mysqli, $publish_schedule),
			      mysqli_real_escape_string($mysqli, $currently_here),
			      mysqli_real_escape_string($mysqli, $_GET['user_id']));

		if ($result = $mysqli->query($query, MYSQLI_STORE_RESULT))
		    $message = "Basic Info Updated";
		else
		    $message = "The user's Basic Information failed to update; talk to a developer to see what's up";

		break;
	    case "certification":
		
		// Update rank
		$query = sprintf("UPDATE users
				  SET rank_id = '%s'
				  WHERE id = '%s'",
			      mysqli_real_escape_string($mysqli, $_POST['rank']),
			      mysqli_real_escape_string($mysqli, $_GET['user_id']));

		if ($mysqli->query($query, MYSQLI_STORE_RESULT))
		    $message .= "Rank Updated<br />";
		else
		    $message .= "The user's rank failed to update; talk to a developer to see what's up<br />";

		// Update certifications
		$query = "SELECT id, name
			  FROM labs
			  WHERE req_cert = 1";

		$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

		// Store lab ids and names in array
		$labs = array();

		while (list($id, $name) = $result->fetch_row()) {
		    $labs[$id] = $name;
		}

		$result->free();

		// Fetch certification info for user and store in array
		$query = sprintf("SELECT lab_id, date
				  FROM certifications
				  WHERE user_id = '%s'",
			      mysqli_real_escape_string($mysqli, $_GET['user_id']));

		$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

		$certs = array();

		while (list($lab_id, $date) = $result->fetch_row()) {
		    $certs[$lab_id] = $date;
		}

		$result->free();

		foreach($labs as $id => $name) {
		    // Create a string that corresponds to the name attribute for each lab in the $_POST array
		    $lab_attr = str_replace(" ","",strtolower($name));

		    // Check 'checked' status of each box
		    $checked = (isset($_POST[$lab_attr])) ? $_POST[$lab_attr] : FALSE;

		    /* If certified and box remains checked - DO NOTHING
		       If certified and box unchecked - DELETE CERT
		       If not certified and box checked - CREATE CERT
		       If not certified and box remains unchecked - DO NOTHING */

		    if (array_key_exists($id,$certs)) {
			if (!$checked) {
			    $query = sprintf("DELETE FROM certifications
					      WHERE user_id = '%s'
					      AND lab_id = $id",
					  mysqli_real_escape_string($mysqli, $_GET['user_id']));

			    if ($mysqli->query($query, MYSQLI_STORE_RESULT))
				$message .= "Removed $name certification<br />";
			    else
				$message .= "There was an error when trying to delete the $name certification<br />
					     Talk to a developer to see what's up<br />";
			}
		    }
		    else {
			if ($checked) {
			    $query = sprintf("INSERT INTO certifications
					      (user_id, lab_id, date)
					      VALUES (%s, $id, '" . date("Y-m-d") . "')",
					  mysqli_real_escape_string($mysqli, $_GET['user_id']));

			    if ($mysqli->query($query, MYSQLI_STORE_RESULT))
				$message .= "$name certification created<br />";
			    else
				$message .= "There was a problem when trying to create the $name certification<br />
					     Talk to a developer to see what's up<br />";
			}
		    }
		}

		break;
	    case "other":

		// First, get the canEat and isA input
		$canEat = "";
		$isA = "";

		if ($result = $mysqli->query("SELECT symbol, type FROM dietary", MYSQLI_STORE_RESULT)) {
		    while (list($symbol, $type) = $result->fetch_row()) {
			if (isset($_POST[$type. $symbol]) && $_POST[$type . $symbol] == $symbol) {
			    $$type .= $symbol;
			}
		    }
		}
		else
		    $message = "Failed to fetch dietary information; talk to a developer to see what's up<br />";

		$result->free();

		/* Then, enter this info into the DB using REPLACE INTO -- if the field exists,
		   REPLACE INTO updates the field; otherwise, it creates a new field with the info */
		$query = sprintf("REPLACE INTO users_data
				  (user_id, birthday, shirtsize, canEat, isA, 
				   fav_sweet, fav_color, fav_food, fav_drink)
				  VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s')",
			      mysqli_real_escape_string($mysqli, $_GET['user_id']),
			      mysqli_real_escape_string($mysqli, $_POST['b_day_y'] . "-" . $_POST['b_day_m'] . "-" . $_POST['b_day_d']),
			      mysqli_real_escape_string($mysqli, $_POST['shirtsize']),
			      mysqli_real_escape_string($mysqli, $canEat),
			      mysqli_real_escape_string($mysqli, $isA),
			      mysqli_real_escape_string($mysqli, $_POST['fav_sweet']),
			      mysqli_real_escape_string($mysqli, $_POST['fav_color']),
			      mysqli_real_escape_string($mysqli, $_POST['fav_food']),
			      mysqli_real_escape_string($mysqli, $_POST['fav_drink']));

		if ($result = $mysqli->query($query, MYSQLI_STORE_RESULT))
		    $message = "Other Info Updated<br />";
		else
		    $message .= "Your Other Information failed to update; talk to a developer to see what's up<br />";

		break;
	    case "password":

		// If we're changing the password, we need to e-mail the user with the new password
		$query = sprintf("SELECT email
				  FROM users
				  WHERE id = '%s'",
			      mysqli_real_escape_string($mysqli, $_GET['user_id']));

		// Only if the query succeeds should we change the password and rock and roll
		if ($result = $mysqli->query($query, MYSQLI_STORE_RESULT)) {

		    $email = '';
		    list ($email) = $result->fetch_row();

		    // Create a random, six-character password
		    $password = '';
		    for ($i = 0; $i < 6; $i++) {
			$password .= chr(round(rand(65,90)));
		    }

		    // UPDATE the password in the DB
		    $query = sprintf("UPDATE users
				      SET password = '%s'
				      WHERE id = '%s'",
				  mysqli_real_escape_string($mysqli, sha1($password)),
				  mysqli_real_escape_string($mysqli, $_GET['user_id']));

		    if ($mysqli->query($query, MYSQLI_STORE_RESULT)) {
			$message = "Password successfully changed";

			// Finally, e-mail the user, letting him know his password was changed
			$to = $email;
			$subject = $config["system_title"] . ' password changed';
			$msg = "Your TCDB password was changed to $password\n\n" . 
			       "Please log on with this new password, change it immediately, and let a TCC know if you have any trouble\n";
			$headers = 'From: password.reset@tcdb.grinnell.edu' . "\r\n" .
				   'Reply-To: ' . $config["system_email"] . "\r\n" .
				   'Cc: ' . $config["system_email"] . "\r\n";

			mail($to, $subject, $msg, $headers);
		    }
		    else
			$message = "The password was not successfully changed";
		}

		break;
	    case "comment":
		$query = sprintf("INSERT INTO user_comments
				  (user_id, comment, date, submitted_by)
				  VALUES ('%s', '%s', '" . date("Y-m-d") . "', '%s')",
			      mysqli_real_escape_string($mysqli, $_GET['user_id']),
			      mysqli_real_escape_string($mysqli,  wordwrap($_POST['comment'], 75, "<br />\n")),
			      mysqli_real_escape_string($mysqli, $_SESSION['username']));

		if ($mysqli->query($query, MYSQLI_STORE_RESULT))
		    $message = "Comment successfully added";
		else
		    $message = "Comment not added successfully; please try again or check the DB connection";

		break;
	    case "delete":
		
		/* Before we delete a user, we want to retain her information in a PDF so that
		   can review the information after the user is gone; that way, we keep the
		   most important information while scrapping the rest */

		// Grab info from users table
		$query = sprintf("SELECT first_name, last_name,
					 hire_date, class,
					 rank_id, semesters
				  FROM users
				  WHERE id= '%s'",
			      mysqli_real_escape_string($mysqli, $_GET['user_id']));

		$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

		list($first_name, $last_name, $hire_date, $class, 
		     $rank_id, $semesters) = $result->fetch_row();

		$result->free();

		// Then grab rank names and store in array
		$query = "SELECT id, name
			  FROM ranks";

		$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

		$ranks = array();

		while (list($id, $name) = $result->fetch_row()) {
		    $ranks[$id] = $name;    
		}

		// Get the total hours worked
		$query = sprintf("SELECT date,
					 TIME_FORMAT(start_time, '%%H'),
					 TIME_FORMAT(start_time,'%%i'),
					 TIME_FORMAT(end_time,'%%H'),
					 TIME_FORMAT(end_time,'%%i')
				  FROM hours_worked
				  WHERE user_id = '%s'
				  ORDER by date",
			      mysqli_real_escape_string($mysqli, $_GET['user_id']));

		// Since we're dealing with a large result set, we want to USE_RESULT
		$result = $mysqli->query($query, MYSQLI_USE_RESULT);

		// We want to keep track of total minutes
		$total_min = 0;

		while (list($date, $start_hr, $start_min, $end_hr, $end_min) = $result->fetch_row()) {
		    $start_total = $start_min + (60 * $start_hr);

		    // If it's past midnight, we have to do a special conversion
		    if ($end_hr < $start_hr)
			$end_total = $end_min + (60 * $end_hr) + (60 * 24);
		    else
			$end_total = $end_min + (60 * $end_hr);

		    $total_min += $end_total - $start_total;
		}

		$total_hours = round($total_min / 60);

		$result->free();

		// Pull lab info from DB (only those that require certification)
		$query = "SELECT id, name
			  FROM labs
			  WHERE req_cert = 1";

		$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

		// Store lab ids and names in array
		$labs = array();

		while (list($id, $name) = $result->fetch_row()) {
		    $labs[$id] = $name;
		}

		$result->free();

		// Fetch certification info for user and store in array
		$query = sprintf("SELECT lab_id, date
				  FROM certifications
				  WHERE user_id = '%s'",
			      mysqli_real_escape_string($mysqli, $_GET['user_id']));

		$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

		$certs = array();

		while (list($lab_id, $date) = $result->fetch_row()) {
		    $certs[$lab_id] = $date;
		}

		$result->free();

		// Create a string of certifications
		$certifications = array();

		foreach($labs as $id => $name) {
		    if (array_key_exists($id, $certs)) {
			$certifications[] = $name;
		    }
		}

		// We want to split the array so we have a grammatically correct string
		$length = count($certifications);
		$split_certs = array_slice($certifications, 0, ($length - 1));
		$cert_string = implode(', ', $split_certs);

		// Create a PDF with employment history
		$pdf=new FPDF();
		$pdf->AddPage();
		$pdf->SetFont('Times','BU',16);
		$pdf->Cell(20,10,"Employment history for $first_name $last_name",0,1);
		$pdf->SetFont('Times','B',12);
		$pdf->Cell(20,10,"$first_name was hired on $hire_date and worked $semesters semesters",0,1);
		$pdf->Cell(20,10,"$first_name graduated in $class",0,1);
		$pdf->Cell(20,10,"$first_name was a " . $ranks[$rank_id] . "",0,1);
		$pdf->Cell(20,10,"$first_name worked $total_hours hours",0,1);

		// Pull lab info from DB (only those that require certification)
		$query = "SELECT id, name
			  FROM labs
			  WHERE req_cert = 1";

		$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

		// Store lab ids and names in array
		$labs = array();

		while (list($id, $name) = $result->fetch_row()) {
		    $labs[$id] = $name;
		}

		$result->free();

		// Fetch certification info for user and store in array
		$query = sprintf("SELECT lab_id, date
				  FROM certifications
				  WHERE user_id = '%s'",
			      mysqli_real_escape_string($mysqli, $_GET['user_id']));

		$result = $mysqli->query($query, MYSQLI_STORE_RESULT);
		
		// If the TC is certified for any special labs, write them to the PDF
		if ($result->num_rows != 0) {

		    $certs = array();

		    while (list($lab_id, $date) = $result->fetch_row()) {
			$certs[$lab_id] = $date;
		    }

		    $result->free();

		    // Create a string of certifications
		    $certifications = array();

		    foreach($labs as $id => $name) {
			if (array_key_exists($id, $certs)) {
			    $certifications[] = $name;
			}
		    }

		    // We want to split the array so we have a grammatically correct string
		    $length = count($certifications);
		    $split_certs = array_slice($certifications, 0, ($length - 1));
		    $cert_string = implode(', ', $split_certs);

		    // Write to PDF
		    $pdf->Cell(20,10,"$first_name worked in the $cert_string and " . $certifications[($length - 1)] . "",0,1);
		}
		
		// Pull existing comments from the DB
		$query = sprintf("SELECT comment, date, submitted_by
				  FROM user_comments
				  WHERE user_id = '%s'
				  ORDER BY date",
			      mysqli_real_escape_string($mysqli, $_GET['user_id']));

		$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

		// If we have any comments, write them to the PDF
		if ($result->num_rows != 0) {

		    $pdf->SetFont('Times','BU',16);
		    $pdf->Cell(20,10,"Comments",0,1);

		    while (list($comment, $comment_date, $submitted_by) = $result->fetch_row()) {
			$pdf->SetFont('Times','I',8);
			$pdf->Cell(20,10,"Submitted on $comment_date by $submitted_by",0,1);
			$pdf->SetFont('Times','B',12);

			// Strip all <br /> tags and write comment
			$pdf->MultiCell(0,5,ereg_replace("<br />", "", $comment));
			$pdf->Ln();
		    }
		}

		$result->free();

		$pdf_name = "History_for_$first_name" . "_$last_name.pdf";

		// Save PDF to the 'employment_history' directory and let user download
		$pdf->Output("employment_history/$pdf_name", 'F');
		$pdf->Output($pdf_name, 'D');

		/* Finally, do the actual deletions. This involves deleting information from
		   the following tables: users, users_data, certifications, and images. We want 
		   to retain information in shifts, since other users may be taking a shift if
		   a user is fired mid-semester; the same follows for sub_requests. Finally, we
		   want to retain information in hours_worked since that's a record of the hours
		   a user worked... and that's important to keep! */

		$query = sprintf("DELETE FROM certifications
				  WHERE user_id = '%s'",
			      mysqli_real_escape_string($mysqli, $_GET['user_id']));

		$mysqli->query($query, MYSQLI_STORE_RESULT);

		$query = sprintf("DELETE FROM images
				  WHERE user_id = '%s'",
			      mysqli_real_escape_string($mysqli, $_GET['user_id']));

		$mysqli->query($query, MYSQLI_STORE_RESULT);

		$query = sprintf("DELETE FROM users_data
				  WHERE user_id = '%s'",
			      mysqli_real_escape_string($mysqli, $_GET['user_id']));

		$mysqli->query($query, MYSQLI_STORE_RESULT);

		$query = sprintf("DELETE FROM users
				  WHERE id = '%s'",
			      mysqli_real_escape_string($mysqli, $_GET['user_id']));

		$mysqli->query($query, MYSQLI_STORE_RESULT);
		
		break;
	}

	// If we're changing anything, we need to update the last_edited time
	$last_updated = date('Y-m-d');

	$query = sprintf("UPDATE users
			  SET last_updated = '$last_updated'
			  WHERE id = '%s'",
		      mysqli_real_escape_string($mysqli, $_GET['user_id']));

	$result = $mysqli->query($query, MYSQLI_STORE_RESULT);
    }

    include('header.php'); 

    echo "  <div class='content_box'> <!-- CONTENT div -->";

    // Now we need to fetch the user data, whether or not it was just changed in the DB

    /** BASIC INFO **/

    // Pull user info from the users and users_data in the DB
    $query = sprintf("SELECT username, first_name, last_name, rank_id, email, campus_phone, cell_phone, 
			     box_num, pcard_id, receive_sub_emails, publish_schedule, currently_here, last_updated, major, 
			     concentration, shirtsize, canEat, isA, fav_sweet, fav_color, fav_food, fav_drink,
			     DATE_FORMAT(birthday, '%%Y'),
			     DATE_FORMAT(birthday, '%%m'),
			     DATE_FORMAT(birthday, '%%d')
		      FROM users LEFT JOIN users_data
		      ON users.id = users_data.user_id
		      WHERE users.id = '%s'",
		mysqli_real_escape_string($mysqli, $_GET['user_id']));

    $result = $mysqli->query($query, MYSQLI_STORE_RESULT);

    // If we get a result set from the query, start to display the information
    if ($result->num_rows != 0) {

	list($username, $first_name, $last_name, $rank_id, $email, $campus_phone, $cell_phone, 
	     $box_num, $pcard_id, $receive_sub_emails, $publish_schedule, $currently_here, $last_updated, $major, 
	     $concentration, $shirtsize, $canEat, $isA, $fav_sweet, $fav_color, $fav_food,
	     $fav_drink, $b_day_y, $b_day_m, $b_day_d) = $result->fetch_row();

	$result->free();

	// Set up initial checked status of checkboxes
	$receive_sub_emails = ($receive_sub_emails) ? "checked='checked'" : "";
	$publish_schedule = ($publish_schedule) ? "checked='checked'" : "";
	$currently_here = ($currently_here) ? "checked='checked'" : "";

	// If we have a message, display it
	if (!empty($message)) {
	    echo "<p class='message'>$message</p>\n";
	}

	echo "    <h2 class='underline'>Edit Info</h2>
	    <div class='left_content'> <!-- LEFT CONTENT div -->
	      <h3 class='underline'>Basic Info</h3>
	      <form id='basic_form' method='post' action='edit_users.php?user_id=" . $_GET['user_id'] . "'>
		<div> <!-- FORM div -->
		  <label for='first_name'>First Name</label>
		  <input class='big_margins' type='text' name='first_name' id='first_name' value='$first_name' /><br />
		  <label for='last_name'>Last Name</label>
		  <input class='big_margins' type='text' name='last_name' id='last_name' value='$last_name' /><br />
		  <label for='email'>E-mail</label>
		  <input class='big_margins' type='text' name='email' id='email' value='$email' /><br />
		  <label for='campus_phone'>Campus Phone</label>
		  <input class='big_margins' type='text' name='campus_phone' id='campus_phone' value='$campus_phone' /><br />
		  <label for='cell_phone'>Cell Phone</label>
		  <input class='big_margins' type='text' name='cell_phone' id='cell_phone' value='$cell_phone' /><br />
		  <label for='box_num'>Box Number</label>
		  <input class='big_margins' type='text' name='box_num' id='box_num' value='$box_num' /><br />
		  <label for='major'>Major</label>
		  <input class='big_margins' type='text' name='major' id='major' value='$major' /><br />
		  <label for='concentration'>Concentration</label>
		  <input class='big_margins' type='text' name='concentration' id='concentration' value='$concentration' /><br />
		  <label for='pcard_id'>P-Card ID</label>
		  <input class='big_margins' type='text' name='pcard_id' id='pcard_id' value='$pcard_id' /><br />
		  <label for='currently_here'>Currently Here?</label>
		  <input class='big_margins' type='checkbox' name='currently_here' id='currently_here' $currently_here /><br />
		  <label for='receive_sub_emails'>Receive Sub Request E-mails?</label>
		  <input class='big_margins' type='checkbox' name='receive_sub_emails' id='receive_sub_emails' $receive_sub_emails /><br />
		  <label for='publish_schedule'>Publish Schedule?</label>
		  <input class='big_margins' type='checkbox' name='publish_schedule' id='publish_schedule' $publish_schedule /><br />
		  <input type='hidden' name='action' value='basic' />
		  <input class='big_margins' type='submit' value='Update Basic Info' /><br />
		</div> <!-- End FORM div -->
	      </form>";

	/** OTHER INFO (B-Day, T-shirt size) **/

	// Print Other Info (birthday, t-shirt size, dietary info)
	echo "	  <h3 class='underline'>Other Info</h3>
	      <form method='post' action='edit_users.php?user_id=" . $_GET['user_id'] . "'>
		<div> <!-- FORM div -->\n";

	// Print Birthday options
	$months = array ("Month", "January", "February", "March", "April",
			 "May", "June", "July", "August", "September",
			 "October", "November", "December");
		
	echo "	  <label for='b_day_m'>Birthday</label>
		  <select name='b_day_m' id='b_day_m'>\n";

	for ($i = 0; $i <= 12; $i++) {
	    if ((!$b_day_m && $i == 0) || $b_day_m == $i) {
		echo "	    <option selected='selected' value='$i'>" . $months[$i] . "</option>\n";
	    }
	    else {
		echo "	    <option value='$i'>" . $months[$i] . "</option>\n";
	    }
	}
		    
	echo "	  </select>\n
		  <select name='b_day_d'>\n";

	if (!$b_day_d || $b_day_d == 0) {
	    echo "	    <option selected='selected' value='0'>Day</option>\n";
	}
	else {
	    echo "	    <option selected='selected' value='0'>Day</option>\n";
	}

	for ($i = 1; $i <= 31; $i++) {
	    if ($b_day_d == $i) {
		echo "	    <option selected='selected' value='$i'>$i</option>\n";
	    }
	    else {
		echo "	    <option value='$i'>$i</option>\n";
	    }
	}

	echo "	  </select>\n
		  <select name='b_day_y'>
		    <option selected='selected' value='0'>Year</option>\n";

	$date_array = getdate();

	for ($i = -15; $i >= -50; $i--) {
	    $temp_year = ($date_array["year"] + $i);
	    if ($b_day_y == $temp_year) {
		echo "	    <option selected='selected' value='$temp_year'>$temp_year</option>\n";
	    }
	    else {
		echo "	    <option value='$temp_year'>$temp_year</option>\n";
	    }
	}

	echo "	  </select><br />\n
		  <label for='shirtsize'>T-Shirt size (S,M,L,XL,XXL)</label>
		  <input class='big_margins' type='text' name='shirtsize' id='shirtsize' size='3' value='$shirtsize' /><br />
		  <label class='bold underline'>Do you eat... ?</label><br />\n";

	/** DIETARY INFO **/

	/* Grab Dietary Info from DB
	   There is a description and symbol pair for each food; for instance,
	   if the description is "Beef", the symbol is "B". We want to pull these
	   pairs from the DB and display a checkbox for each with the proper
	   description and symbol. Thanks to CM Lubinski for this one -- it's 
	   really quite elegant */

	$query = "SELECT description, symbol
		  FROM dietary
		  WHERE type='canEat'";

	$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

	while (list($description, $symbol) = $result->fetch_row()) {
	    if (strpos($canEat, $symbol) !== false) {
		echo "	  <input type='checkbox' name='canEat" . $symbol .
			  "' value='" . $symbol . "' checked='checked' /> " . $description . "<br />\n";
	    }
	    else {
		echo "	  <input type='checkbox' name='canEat" . $symbol .
			  "' value='" . $symbol . "' /> " . $description . "<br />\n";
	    }
	}	

	$result->free();

	// We're doing the same as above, just for Veggy/Vegan info
	echo "	  <br />\n
		  <label class='bold underline'>Are you a... ?</label><br />\n";

	$query = "SELECT description,symbol
		  FROM dietary
		  WHERE type='isA'";
		
	$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

	while (list($description, $symbol) = $result->fetch_row()) {
	    if (strpos($isA, $symbol) !== false) {
		echo "	  <input type='checkbox' name='isA" . $symbol .
			  "' value='" . $symbol . "' checked='checked' /> " . $description . "<br />\n";
	    }
	    else {
		echo "	  <input type='checkbox' name='isA" . $symbol .
			  "' value='" . $symbol . "' /> " . $description . "<br />\n";
	    }
	}	

	$result->free();

	// Print the rest of the other info
	echo "	  <br />\n
		  <label for='fav_sweet'>Favorite sweet/candy</label>
		  <input class='big_margins' type='text' name='fav_sweet' id='fav_sweet' value='$fav_sweet' /><br />
		  <label for='fav_food'>Favorite food/flavor</label>
		  <input class='big_margins' type='text' name='fav_food' id='fav_food' value='$fav_food' /><br />
		  <label for='fav_drink'>Favorite drink</label>
		  <input class='big_margins' type='text' name='fav_drink' id='fav_drink' value='$fav_drink' /><br />
		  <label for='fav_color'>Favorite color</label>
		  <input class='big_margins' type='text' name='fav_color' id='fav_color' value='$fav_color' /><br />
		  <input type='hidden' name='action' value='other' />
		  <input class='big_margins' type='submit' value='Update Other Info' /><br />
		</div> <!-- End FORM div -->
	      </form>

	      <h3 class='underline'>Reset Password</h3>
	      <form method='post' action='edit_users.php?user_id=" . $_GET['user_id'] . "'>
		<div> <!-- FORM div -->
		  <input type='hidden' name='action' value='password' />
		  <input class='big_margins' type='submit' value='Reset Password' />
		</div> <!-- End FORM div -->
	      </form>
	    </div> <!-- End LEFT CONTENT div -->
	    <div class='right_content'> <!-- RIGHT CONTENT div -->
	      <h3 class='underline'>Current Picture</h3>";

	/** USER IMAGE **/

	// Fetch image
	$query = "SELECT user_id
		  FROM images
		  WHERE user_id='" . $_GET['user_id'] . "'";

	$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

	// If we get a result, show image; otherwise, display an error
	if ($result->num_rows != 0) {
	    echo "<a href='edit_photo.php?user_id=" . $_GET['user_id'] . "'><img src='display_image.php?id=" . $_GET['user_id'] . "&amp;buffer=0'
						alt='Image of $username' class='no_border' /></a><br />
		  <p class='bold small_text'>Click on $first_name's photo to edit it</p>\n";
	}
	else {
	    echo "<h3>IMAGE UNAVAILABLE</h3>
	    <p class='bold small_text'><a href='edit_photo.php?user_id=" . $_GET['user_id'] . "'>Edit</a> $first_name's photo</p>\n";
	}

	$result->free();

	// Start to print Rank and Certification information
	echo "	  <h3 class='underline'>Rank and Certification Info</h3>
	      <form method='post' action='edit_users.php?user_id=" . $_GET['user_id'] . "'>
		<div> <!-- FORM div -->\n";

	/** RANK INFO **/

	// Pull ranks info from DB and print, defaulting to current rank
	$query = "SELECT id, name
		  FROM ranks";

	$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

	echo "<label for='rank'>Rank</label>
	<select name='rank' id='rank'>\n";

	while (list($id, $name) = $result->fetch_row()) {
	    if ($id == $rank_id) {
		echo "<option selected='selected' value='$id'>$name</option>\n";
	    }
	    else {
		echo "<option value='$id'>$name</option>\n";
	    }
	}

	$result->free();

	echo "</select><br />\n";

	/** CERTIFICATION INFO **/

	// Pull lab info from DB (only those that require certification)
	$query = "SELECT id, name
		  FROM labs
		  WHERE req_cert = 1";

	$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

	// Store lab ids and names in array
	$labs = array();

	while (list($id, $name) = $result->fetch_row()) {
	    $labs[$id] = $name;
	}

	$result->free();

	// Fetch certification info for user and store in array
	$query = sprintf("SELECT lab_id, date
			  FROM certifications
			  WHERE user_id = '%s'",
		      mysqli_real_escape_string($mysqli, $_GET['user_id']));

	$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

	$certs = array();

	while (list($lab_id, $date) = $result->fetch_row()) {
	    $certs[$lab_id] = $date;
	}

	$result->free();

	// Now print some certs!
	echo "<h4 class='underline'>Certifications</h4>";

	foreach($labs as $id => $name) {
	    // Create a string to use as an attribute for each lab
	    $lab_attr = str_replace(" ","",strtolower($name));

	    echo "<label for='$lab_attr'>$name</label>\n";

	    // If we have a matching lab_id in $certs, the TC is certified and the box should be checked
	    if (array_key_exists($id, $certs)) {
		echo "<input type='checkbox' name='$lab_attr' id='$lab_attr'
			     value='$lab_attr' checked='checked' /><br />\n";
	    }
	    else {
		echo "<input type='checkbox' name='$lab_attr' id='$lab_attr'
			     value='$lab_attr' /><br />\n";
	    }
	}

	echo "<input type='hidden' name='action' value='certification' />    
	    <input class='big_margins' type='submit' value='Update Rank/Cert Info' /><br />
	  </div> <!-- End FORM div -->
	</form>";

	/** COMMENTS **/

	echo "<h3 class='underline'>Comments on $first_name $last_name</h3>\n";

	// Pull existing comments, if any, from the DB
	$query = sprintf("SELECT comment, date, submitted_by
			  FROM user_comments
			  WHERE user_id = '%s'
			  ORDER BY date",
		      mysqli_real_escape_string($mysqli, $_GET['user_id']));

	$result = $mysqli->query($query, MYSQLI_STORE_RESULT);

	// If we have any comments, display them
	if ($result->num_rows != 0) {
	    while (list($comment, $comment_date, $submitted_by) = $result->fetch_row()) {
		echo "<h4>Submitted on $comment_date by $submitted_by</h4>
		<p>$comment</p>\n";
	    }
	}
	else
	    echo "<h4>There are no comments for $first_name $last_name</h4>\n";
	    
	$result->free();
	
	// Now, display a box to add additional comments
	echo "<h4>Add New Comment</h4>
	<form method='post' action='edit_users.php?user_id=" . $_GET['user_id'] . "'>
	  <div> <!-- FORM div -->
	    <textarea name='comment' cols='40' rows='5'></textarea><br />
	    <input type='hidden' name='action' value='comment' />
	    <input type='submit' value='Submit Comment' /><br />
	  </div> <!-- End FORM div -->
	</form>";

	/** DELETE USER **/

	// Javascript to prompt for user deletion (so we don't accidentally delete a user)

	echo "<h3 class='underline'>Delete User</h3>
	<script src='javascript/jquery/plugins/jquery-alerts/jquery.alerts.js' type='text/javascript'></script>
	<script src='javascript/jquery/development-bundle/ui/ui.draggable.js' type='text/javascript'></script>
	<link rel='stylesheet' type='text/css' href='javascript/jquery/plugins/jquery-alerts/jquery.alerts.css' />
	<script type='text/javascript'>
	$(document).ready( function() {
	    $('#confirm_button').click( function() {
		jConfirm('Are you sure you want to delete this user?', 'Delete User', function(r) {
		    if (r) {
			document.getElementById('delete_user').submit();
		    }
		});
	    });
	});
	</script>

	<form id='delete_user' method='post' action='edit_users.php?user_id=" . $_GET['user_id'] . "'>
	  <div> <!-- FORM div -->
	    <input type='hidden' name='action' value='delete' />
	    <input id='confirm_button' type='button' value='Delete User' /><br />
	  </div> <!-- End FORM div -->
	</form>

	<p id='last_updated_footer'>Info Last Updated: $last_updated</p>
      </div> <!-- End RIGHT CONTENT div -->";
    }

    else 
	echo "  <h2>Cannot display information -- the specified user ID doesn't exist</h2>\n";
}

echo "</div> <!-- End CONTENT div -->\n";

include('footer.php'); 

?> 
